package 浏览器环境类

import (
	"fmt"
	"gitee.com/go_888/webview2/internal/w32"
	"github.com/lxn/walk"
	"github.com/lxn/walk/declarative"
	"github.com/lxn/win"
)

type Window struct {
	*walk.MainWindow
}

var 窗口 = new(Window)
var 编辑框 *walk.TextEdit

func X运行窗口() {
	if err := (declarative.MainWindow{
		AssignTo: &窗口.MainWindow,
		Title:    "正在下载缺失的运行环境.....",
		Size:     declarative.Size{400, 260},
		Layout:   declarative.VBox{},
		Children: []declarative.Widget{
			declarative.TextEdit{
				AssignTo: &编辑框,
				VScroll:  true,
				ReadOnly: true,
			},
		},
	}.Create()); err != nil {
		fmt.Println(err)
	}

	窗口.居中显示()
	窗口.删除窗口样式(^win.WS_MAXIMIZEBOX) // 禁止最大化
	窗口.删除窗口样式(^win.WS_MINIMIZEBOX) // 隐藏最小化按钮
	窗口.删除窗口样式(^win.WS_THICKFRAME)  // 禁止拖动
	窗口.设置窗口置顶(true)

	//窗口.Closing().Attach(func(canceled *bool, reason walk.CloseReason) {
	//	msgBox := walk.MsgBox(窗口, "确认关闭", "正在初始化缺失环境, 确定要关闭吗？", walk.MsgBoxYesNo|walk.MsgBoxIconQuestion)
	//	if msgBox == walk.DlgCmdYes {
	//		*canceled = false // 允许关闭
	//	} else {
	//		*canceled = true // 取消关闭
	//	}
	//})
	窗口.Run()
}
func X是否已关闭() bool {
	return 窗口.IsDisposed()
}

func X关闭() {
	窗口.Close()
}
func X追加日志(日志 string) {
	if 编辑框.IsDisposed() == false {
		编辑框.AppendText(日志 + "\r\n")
	}
}
func X设置窗口标题(标题 string) {
	if 窗口.IsDisposed() == false {
		窗口.SetTitle(标题)
	}
}

func (mw *Window) 删除窗口样式(样式 int32) {
	currStyle := win.GetWindowLong(mw.Handle(), win.GWL_STYLE)
	win.SetWindowLong(mw.Handle(), win.GWL_STYLE, currStyle&样式)
}

// 居中显示 将窗口居中显示在屏幕上
func (mw *Window) 居中显示() {
	screenWidth := int(win.GetSystemMetrics(win.SM_CXSCREEN))
	screenHeight := int(win.GetSystemMetrics(win.SM_CYSCREEN))

	windowWidth := mw.Width()
	windowHeight := mw.Height()

	x := (screenWidth - windowWidth) / 2
	y := (screenHeight - windowHeight) / 2
	mw.SetBounds(walk.Rectangle{x, y, windowWidth, windowHeight})
}

func (w *Window) 设置窗口置顶(启用 bool) {
	flag := w32.HWND_NOTOPMOST
	if 启用 {
		flag = w32.HWND_TOPMOST
	}
	_, _, _ = w32.X设置窗口位置和尺寸.Call(
		uintptr(w.Handle()),
		uintptr(flag),
		0, 0, 0, 0,
		w32.SWP_NOMOVE|w32.SWP_NOSIZE,
	)
}
